package com.jxdinfo.hussar.example.qjgl.ryqjsjmx.service.impl;

import com.jxdinfo.hussar.support.mp.base.service.impl.HussarServiceImpl;
import com.jxdinfo.hussar.support.datasource.annotations.HussarDs;
import com.jxdinfo.hussar.support.exception.HussarException;
import com.jxdinfo.hussar.platform.core.utils.HussarUtils;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.model.Ryqjsjmx;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.service.RyqjsjmxService;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.dao.RyqjsjmxMapper;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxdinfo.hussar.workflow.manage.engine.TaskEngineService;
import com.jxdinfo.hussar.common.tfmodel.TfModelEnum;
import com.jxdinfo.hussar.common.security.BaseSecurityUtil;
import com.jxdinfo.hussar.support.transaction.core.annotation.HussarTransactional;
import com.jxdinfo.hussar.workflow.engine.response.BpmResponseResult;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.jxdinfo.hussar.support.mp.base.query.generator.SingleTableQueryGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import com.jxdinfo.hussar.support.mp.base.query.generator.superquery.SuperQueryGenerator;
import org.springframework.aop.framework.AopContext;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.dto.RyqjsjmxDto;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.vo.RyqjsjmxPageVO;
import com.jxdinfo.hussar.platform.core.base.apiresult.ApiResponse;
import java.util.ArrayList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import com.jxdinfo.hussar.workflow.engine.constant.BpmConstant;
import java.util.Map;
import com.jxdinfo.hussar.example.qjgl.ryqjsjmx.dto.RyqjsjmxRyqjsjmxdataset1;
import com.jxdinfo.hussar.workflow.manage.engine.InstanceEngineService;
import com.alibaba.fastjson.JSONObject;
import java.util.Collections;

/**
 * 人员请假数据模型服务实现类
 */
@Service("qjgl.ryqjsjmx.RyqjsjmxServiceImpl")
@HussarDs("master")
public class RyqjsjmxServiceImpl extends HussarServiceImpl<RyqjsjmxMapper, Ryqjsjmx> implements RyqjsjmxService {

    private static final Logger logger = LoggerFactory.getLogger(RyqjsjmxServiceImpl.class);

    private static final String RETURN_CODE = "0";

    @Autowired
    private RyqjsjmxMapper ryqjsjmxMapper;

    @Override
    public ApiResponse<Ryqjsjmx> formQuery(String id) {
        try {
            return ApiResponse.success(this.getById(id));
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    @HussarTransactional
    public ApiResponse<String> flowFormSaveStart(RyqjsjmxDto ryqjsjmxDto) {
        try {
            Ryqjsjmx ryqjsjmx = ryqjsjmxDto.getFormdata();
            String processDefinitionKey = ryqjsjmxDto.getProcessDefinitionKey() == null ? "" : ryqjsjmxDto.getProcessDefinitionKey();
            this.saveOrUpdate(ryqjsjmx);
            String businessKey = String.valueOf(ryqjsjmx.getId());
            ApiResponse<?> flowApiResponse = ((RyqjsjmxService) AopContext.currentProxy()).startSaveProcessInstance(processDefinitionKey, businessKey);
            if (flowApiResponse.isSuccess()) {
                return ApiResponse.success(String.valueOf(ryqjsjmx.getId()), "");
            }
            throw new HussarException(flowApiResponse.getMsg());
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public ApiResponse<String> startSaveProcessInstance(String processDefinitionKey, String businessKey) {
        BpmResponseResult isstartResult;
        try {
            isstartResult = InstanceEngineService.checkProcessInstByBusinessKey(businessKey);
            if (BpmConstant.SUCCESS_CODE.equals(isstartResult.getCode())) {
                if (HussarUtils.isEmpty(BaseSecurityUtil.getUser())) {
                    throw new HussarException(TfModelEnum.TF_FAILED_T0_OBTAIN_USER_INFORMATION.getMessage());
                }
                String userId = String.valueOf(BaseSecurityUtil.getUser().getId());
                BpmResponseResult startResult;
                startResult = InstanceEngineService.startProcessInstanceByKey(processDefinitionKey, userId, businessKey, null);
                if (BpmConstant.SUCCESS_CODE.equals(startResult.getCode())) {
                    return ApiResponse.success(startResult.getMsg());
                } else {
                    throw new HussarException(startResult.getMsg());
                }
            } else {
                return ApiResponse.success("");
            }
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    public ApiResponse<RyqjsjmxPageVO> hussarQueryPage(Page<Ryqjsjmx> page) {
        try {
            Page<Ryqjsjmx> pager = new Page<>(page.getCurrent(), page.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (page.orders() != null) {
                for (OrderItem orderItem : page.orders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            RyqjsjmxPageVO ryqjsjmxPageVO = new RyqjsjmxPageVO();
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Ryqjsjmx> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Ryqjsjmx(), parameterMap);
            List<Ryqjsjmx> list = this.page(pager, queryWrapper).getRecords();
            ryqjsjmxPageVO.setData(list);
            ryqjsjmxPageVO.setCount(pager.getTotal());
            ryqjsjmxPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(ryqjsjmxPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    public ApiResponse<RyqjsjmxPageVO> hussarQueryPage_order_custom(Page<Ryqjsjmx> page) {
        try {
            Page<Ryqjsjmx> pager = new Page<>(page.getCurrent(), page.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (page.orders() != null) {
                for (OrderItem orderItem : page.orders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            RyqjsjmxPageVO ryqjsjmxPageVO = new RyqjsjmxPageVO();
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Ryqjsjmx> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Ryqjsjmx(), parameterMap);
            List<Ryqjsjmx> list = this.page(pager, queryWrapper).getRecords();
            ryqjsjmxPageVO.setData(list);
            ryqjsjmxPageVO.setCount(pager.getTotal());
            ryqjsjmxPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(ryqjsjmxPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    @HussarTransactional
    public ApiResponse<String> flowFormSubmitReject(RyqjsjmxDto ryqjsjmxDto) {
        Ryqjsjmx ryqjsjmx = ryqjsjmxDto.getFormdata();
        try {
            this.saveOrUpdate(ryqjsjmx);
            String returnCode = ((RyqjsjmxService) AopContext.currentProxy()).formsubmitreject(ryqjsjmxDto, String.valueOf(ryqjsjmx.getId()));
            if (BpmConstant.SUCCESS_CODE.equals(returnCode)) {
                return ApiResponse.success(TfModelEnum.TF_PROCESS_FORM_WAS_SUCCESSFULLY_SUBMITTED.getMessage());
            } else {
                throw new HussarException(TfModelEnum.TF_FAILED_TO_SUBMIT_THE_PROCESS_FORM.getMessage());
            }
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public String formsubmitreject(RyqjsjmxDto ryqjsjmxDto, String businessKey) {
        if (HussarUtils.isEmpty(BaseSecurityUtil.getUser())) {
            throw new HussarException(TfModelEnum.TF_FAILED_T0_OBTAIN_USER_INFORMATION.getMessage());
        }
        Map<String, String> appointMap = new HashMap<>();
        Map<String, Object> variable = new HashMap<>();
        try {
            String taskId = ryqjsjmxDto.getTaskId();
            String comment = ryqjsjmxDto.getComment();
            if (ryqjsjmxDto.getFlowSelect() == null) {
                appointMap.put(BpmConstant.STATIC_APPOINT_ASSIGNEE, ryqjsjmxDto.getParticipantSelect());
            } else {
                appointMap.put(ryqjsjmxDto.getFlowSelect(), ryqjsjmxDto.getParticipantSelect());
                variable.put(BpmConstant.BPM_NEXT_NODE, ryqjsjmxDto.getFlowSelect());
            }
            if (ryqjsjmxDto.getSelectBranches() != null) {
                List<String> nextNodeIds = new ArrayList<>();
                for (Map<String, String> map : ryqjsjmxDto.getSelectBranches()) {
                    appointMap.put(map.get("flowSelect"), map.get("participants"));
                    nextNodeIds.add(map.get("flowSelect"));
                }
                variable.put(BpmConstant.BPM_NEXT_NODE, String.join(",", nextNodeIds));
            }
            // 判断是否设置会签
            if (ryqjsjmxDto.getMultiType() != null) {
                variable.put(BpmConstant.MULTI_TYPE, ryqjsjmxDto.getMultiType());
                variable.put(BpmConstant.MULTI_FINISH_CONDITION, ryqjsjmxDto.getMultiFinishCondition());
            }
            String processDefinitionKey = ryqjsjmxDto.getProcessDefinitionKey();
            String userId = String.valueOf(BaseSecurityUtil.getUser().getId());
            if (HussarUtils.isEmpty(taskId)) {
                BpmResponseResult startResult;
                startResult = InstanceEngineService.startProcessInstanceByKey(processDefinitionKey, userId, businessKey, null);
                if (BpmConstant.SUCCESS_CODE.equals(startResult.getCode())) {
                    taskId = (String) startResult.getResult().getJSONObject(0).get("taskId");
                } else {
                    throw new HussarException(TfModelEnum.TF_FAILED_TO_CREATE_A_START_NODE.getMessage());
                }
            }
            BpmResponseResult bpmResponseResult = TaskEngineService.completeLeapTask(taskId, userId, appointMap, null, comment, variable);
            return bpmResponseResult.getCode();
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    public ApiResponse<RyqjsjmxPageVO> hussarQueryryqjsjmxCondition_1Page(RyqjsjmxRyqjsjmxdataset1 ryqjsjmxdataset1) {
        try {
            RyqjsjmxPageVO ryqjsjmxPageVO = new RyqjsjmxPageVO();
            Page<Ryqjsjmx> pager = new Page<>(ryqjsjmxdataset1.getCurrent(), ryqjsjmxdataset1.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (ryqjsjmxdataset1.getOrders() != null) {
                for (OrderItem orderItem : ryqjsjmxdataset1.getOrders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            ryqjsjmxdataset1.setRyqjsjmxenameFullLike(ryqjsjmxdataset1.getRyqjsjmxenameFullLike().replaceAll("/", "//").replaceAll("%", "/%").replaceAll("_", "/_").replaceAll("\\[", "/[").replaceAll("]", "/]"));
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Ryqjsjmx> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Ryqjsjmx(), parameterMap);
            List<Ryqjsjmx> list = ryqjsjmxMapper.hussarQueryryqjsjmxCondition_1Page(pager, ryqjsjmxdataset1, queryWrapper);
            ryqjsjmxPageVO.setData(list);
            ryqjsjmxPageVO.setCount(pager.getTotal());
            ryqjsjmxPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(ryqjsjmxPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    public ApiResponse<RyqjsjmxPageVO> hussarQueryryqjsjmxCondition_1Page_order_custom(RyqjsjmxRyqjsjmxdataset1 ryqjsjmxdataset1) {
        try {
            RyqjsjmxPageVO ryqjsjmxPageVO = new RyqjsjmxPageVO();
            Page<Ryqjsjmx> pager = new Page<>(ryqjsjmxdataset1.getCurrent(), ryqjsjmxdataset1.getSize());
            Map<String, String[]> parameterMap = new HashMap<>();
            String[] orderParameter = new String[1];
            if (ryqjsjmxdataset1.getOrders() != null) {
                for (OrderItem orderItem : ryqjsjmxdataset1.getOrders()) {
                    if (orderItem.isAsc()) {
                        orderParameter[0] = orderItem.getColumn() + ",asc;";
                    } else {
                        orderParameter[0] = orderItem.getColumn() + ",desc;";
                    }
                }
            }
            parameterMap.put("orderRule", orderParameter);
            ryqjsjmxdataset1.setRyqjsjmxenameFullLike(ryqjsjmxdataset1.getRyqjsjmxenameFullLike().replaceAll("/", "//").replaceAll("%", "/%").replaceAll("_", "/_").replaceAll("\\[", "/[").replaceAll("]", "/]"));
            // 查询条件构造器,将排序条件封装成QueryWrapper
            SingleTableQueryGenerator singleTableQueryGenerator = new SingleTableQueryGenerator();
            QueryWrapper<Ryqjsjmx> queryWrapper = singleTableQueryGenerator.initQueryWrapper(new Ryqjsjmx(), parameterMap);
            List<Ryqjsjmx> list = ryqjsjmxMapper.hussarQueryryqjsjmxCondition_1Page_order_custom(pager, ryqjsjmxdataset1, queryWrapper);
            ryqjsjmxPageVO.setData(list);
            ryqjsjmxPageVO.setCount(pager.getTotal());
            ryqjsjmxPageVO.setCode(RETURN_CODE);
            return ApiResponse.success(ryqjsjmxPageVO);
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_FORM_QUERY_FAILED.getMessage());
        }
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public ApiResponse<JSONObject> flowTableUpdate(RyqjsjmxDto ryqjsjmxDto) {
        try {
            return InstanceEngineService.validateEditAuthority(ryqjsjmxDto.getUpdateRowId());
        } catch (Exception e) {
            throw new HussarException(TfModelEnum.TF_PROCESS_TABLE_IS_ABNORMALLY_MODIFIED.getMessage() + e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    public ApiResponse<String> flowTableDelete(String id) {
        try {
            this.removeByIds(Collections.singletonList(id));
            return ((RyqjsjmxService) AopContext.currentProxy()).deleteProcessInstance(id);
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    public ApiResponse<String> flowTableDeleteUnStart(String id) {
        // 验证流程状态
        BpmResponseResult validateResult;
        try {
            validateResult = ((RyqjsjmxService) AopContext.currentProxy()).getValidateResult(id);
            if (BpmConstant.SUCCESS_CODE.equals(validateResult.getCode())) {
                String state = validateResult.getResult().get(0) == null ? "" : validateResult.getResult().get(0).toString();
                switch(state) {
                    // 1 代表流程已经启动，并且节点处于第一节点，可以删除业务数据和流程数据
                    case BpmConstant.SUCCESS_CODE:
                        // 删除业务数据
                        this.removeByIds(Collections.singletonList(id));
                        // 删除流程数据
                        return ((RyqjsjmxService) AopContext.currentProxy()).deleteProcessInstance(id);
                    // 2 代表流程已经启动，并且节点不处于第一节点，不可以删除业务数据和流程数据
                    case "2":
                        logger.error(validateResult.getMsg());
                        throw new HussarException(validateResult.getMsg());
                    // 0 代表流程没有启动，可以删除业务数据，不需要删除流程数据
                    case BpmConstant.ERROR_CODE:
                        // 删除业务数据
                        this.removeByIds(Collections.singletonList(id));
                        return ApiResponse.success("");
                    default:
                        throw new HussarException(TfModelEnum.TF_DELETION_FAILED.getMessage());
                }
            }
            throw new HussarException(TfModelEnum.TF_DELETION_FAILED.getMessage());
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public BpmResponseResult getValidateResult(String id) {
        return InstanceEngineService.validateDeleteByBusinessKey(String.valueOf(id));
    }

    @Override
    @HussarTransactional
    @HussarDs("master")
    public ApiResponse<String> deleteProcessInstance(String id) {
        BpmResponseResult bpmResponseResult;
        try {
            bpmResponseResult = InstanceEngineService.deleteProcessInstanceByBusinessKey(id);
            if (BpmConstant.SUCCESS_CODE.equals(bpmResponseResult.getCode())) {
                return ApiResponse.success("");
            }
            return ApiResponse.fail(bpmResponseResult.getMsg());
        } catch (Exception e) {
            throw new HussarException(e.getMessage());
        }
    }
}
